﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;

namespace YmtAuth.Repository.DapperRepository
{
    public class ParametersWrapper
    {
        private readonly DynamicParameters par;
        public ParametersWrapper()
        {
            par = new DynamicParameters();
        }

        public static ParametersWrapper Factory
        {
            get { return new ParametersWrapper(); }
        }

        public ParametersWrapper Add(string name, object val, DbType type)
        {
            par.Add(name, val, type);
            return this;
        }

        public ParametersWrapper Add(string name, object val)
        {
            par.Add(name, val);
            return this;
        }

        public ParametersWrapper AddXml(string name, object[] val)
        {
            par.Add(name, ParseArrayValue(val), DbType.Xml);
            return this;
        }

        public ParametersWrapper AddLong(string name, Int64 val)
        {
            par.Add(name, val, DbType.Int64);
            return this;
        }
        public ParametersWrapper AddInt(string name, Int32 val)
        {
            par.Add(name, val, DbType.Int32);
            return this;
        }
        public ParametersWrapper AddString(string name, string val,int? len=null)
        {
            par.Add(name, val, DbType.String,size:len);
            return this;
        }

        public ParametersWrapper AddDateTime(string name, DateTime dateTime)
        {
            par.Add(name, dateTime, DbType.DateTime);
            return this;
        }

        public ParametersWrapper AddByte(string name, byte val)
        {
            par.Add(name, val, DbType.Byte);
            return this;
        }

        public DynamicParameters Build()
        {
            return this.par;
        }
        private string ParseArrayValue(object[] value)
        {
            var str = new StringBuilder("<root>");
            foreach (var val in value)
            {
                str.Append("<k v='").Append(val).Append("'/>");
            }
            str.Append("</root>");
            return str.ToString();
        }
    }
}
